<?php
/*
Klasse zum Parsen eines Galaxiestrings - gleichzeitiges einf?n die DB
*/

//include_once "languages.php";
include_once "attributes.php";
include_once("../debug.php");

class Parser {

	var $error = "";     // Fehlermeldung fals eine Methode false zur?fert

	var $dbusername  = "";
	var $dbpassword  = "";
	var $dbname      = "";
	var $dbhost      = "";
	var $tablename   = ""; // Galaxie Tabelle
	var $pstatsname  = ""; // Spielerstats Tabelle
	var $astatsname  = ""; // Allystats Tabelle
	var $noticetable = ""; // Notizen Tabelle
    var $reporttable = ""; // Reports Tabelle
	
	var $parserarray = null;

	/**
	* @return downloads
	* @param String $dbusername Datenbanknutzername
	* @param String $dbpassword Datenbankpasswort
	* @param String $dbname Name der Datenbank
	* @param String $tablename Name der Tabelle mit den Downloads
	* @param String $dbhost Datenbankadresse
	* @desc Konstruktor der Klasse downloads
 	*/
	function parser($dbusername,$dbpassword,$dbname,$tablename,$astatstable,$plstatstable,$noticetable,$reporttable,$dbhost="localhost") {

		if (!($this->_set_dbusername($dbusername))) die($this->error);
		if (!($this->_set_dbname($dbname))) die($this->error);
		if (!($this->_set_tablename($tablename))) die($this->error);
		$this->dbpassword = $dbpassword;
		$this->astatsname = (!empty($astatstable)) ? $astatstable : "tabelle4";
		$this->pstatsname = (!empty($plstatstable)) ? $plstatstable : "tabelle3";
		$this->noticetable = (!empty($noticetable)) ? $noticetable : "tabelle5";
		$this->reporttable = (!empty($reporttable)) ? $reporttable : "tabelle6";
		$this->_set_dbhost($dbhost);
		$this->_db_connection_works(); // Testen der Datenbankverbindung
	}




	/**
	* @return void
	* @param String $galastring String der in Galaxieansicht kopiert wurde.
	* @desc Analysiert den String und f?ie DB mit den Daten
	*/
	function parseString($galastring,$return=false,$fixnotices=true) {
		global $default_server;

		$userid = $_SESSION['s_userid'];
		$ogameserver = $_SESSION['s_ogameserver'];
		
		$returnarray = array(); // wird ben?t bei return = true;

		$galastring = trim($galastring);
		$string = $galastring;

		
		// "Sonnensystem" suchen
		$found = false;
		$i = 0;

		while (!$found) {
			$i++;
			$pos = strpos($string,"Solar system");
			if($pos === false) return false;
			$temp = substr($string,$pos+1+strlen("Solar system"),1);
			if (is_numeric($temp)) $found = true;
			$string = substr($string,$pos+strlen("Solar system"));
			if ($i == 10) return false; // um Endlosschleife zu verhindern
		}
		$rest = trim($string);
		$galaxie = substr($rest,0,strpos($rest,":"));
		$string  = strstr($rest,":");  // liefer Rest nach dem Doppelpunkt hinter der Galaxie
		$system  = substr($string,0,4);
		$system  = preg_replace("/([^0-9])/","",$system);

		$string = strstr($string,"\n");  // liefer Rest nach dem Doppelpunkt hinter der Galaxie
		$line = explode("\n",$string);

		$infoarray = array();
		
		// Galaxiedaten eintragen
		$allystats = array();
		$playerstats = array();
		
		$matches = array();
		
		for ($i=2;$i<17;$i++) {
			$ally          = "";
			$planetname    = "";
			$planetnummer  = "";
			$spielername   = "";
			$spielerstatus = "";
			unset($mond);

			// Pr?b IE (keine \t sondern nur Leerzeichen)
			if (strpos($line[$i],"\t") === false && strlen($line[$i]) > 3) {
				// IE Handling
				$content = preg_split("/[\s]+\s/",$line[$i], -1);
				$planetnummer = (int)trim($content[0]);
				$inc = 0;
				if (count($content) > 2) {
					if(empty($content[1])){
						$inc = 1;
					}
	    				$planetname = trim($content[1+$inc]);
	    				// Mond wird im IE nicht als M angezeigt - muss dort moonsize ermittelt werden
	    				// Galaxieansicht vom Mond ist im IE wieder anders, da (activity) eine extra Spalte ist.
	    				if (substr($content[2+$inc],0,1) == "(") {
	    				    $spielername = trim($content[3+$inc]);
	    				    $ally = trim($content[4+$inc]);
	    				} else {
	    				    $spielername = trim($content[2+$inc]);
	    				    $ally = trim($content[3+$inc]);
	    				}
				}
			} else {
				// Mozilla, FF, Epiphany etc.
				$content = explode("\t",$line[$i]);
				// use extra variable $inc here, because sometime we can not get the 2nd. column "planet picture"
				$inc = 0;
				if (count($content) > 2) {
					if(empty($content[1])){
						$inc = 1;
					}
					$planetnummer = (int)trim($content[0]);
					if (count($content) > 2) {
					    $planetname = trim($content[1+$inc]);
					    $mond = (substr(trim($content[2+$inc]),0,1) == "M") ? 1 : 0;
					    $spielername = 	trim($content[4+$inc]);
					    $ally = trim($content[5+$inc]);
					}
				}
			}


			// Planetname ermitteln
			if (!empty($planetname)) {
				$pos = strpos($planetname,"(");
				if ($pos !== false ) $planetname = trim(substr($planetname,0,$pos));
			}

			// Spielerstatu				rmitteln
			if (!empty($spielername)) {
				$pos = strpos($spielername,"(");
				$pos2 = strpos($spielername,")");
				if ((($pos !== false) && ($pos !== false))) {
					$spielerstatus = trim(substr($spielername,$pos+1,$pos2-$pos-1));
					if($ogameserver=='ogame.org'){
						$spielerstatus = str_replace("b","g",$spielerstatus); // english+french+italian banned players
						$spielerstatus = str_replace("v","u",$spielerstatus); // english+spanish+dutch+french+italian vacation mode
					}
					$spielerstatus = preg_replace('/[^iIugns]/i','', $spielerstatus);
					$spielername = trim(substr($spielername,0,$pos));
				}
			}

			$infoarray['['.$galaxie.":".$system.":".$planetnummer."]"] = array(
				"galaxie" => $galaxie,
				"system" => $system,
				"planetnummer" => $planetnummer,
				"ally" => $ally,
				"planetname" => $planetname,
				"playername" => $spielername,
				"playerstatus" => $spielerstatus
			);
			$infoarray['['.$galaxie.":".$system.":".$planetnummer."]"]['moon'] = (isset($mond) && $mond == 1) ? 1 : 0;
			if(!empty($spielername) && !isset($playerstats[$spielername])){
				$playerstats[$spielername] = array('status'=>'', 'ally'=>'', 'rank'=>-1);
				$playerstats[$spielername]['status'] = $spielerstatus;
				$playerstats[$spielername]['ally'] = $ally;
			}
		}

		// Zusatzinfos sammeln
		if($ogameserver=='ogame.org'){
			// new english
			$galastring = str_replace("ranked","Rank",$galastring);
		} else if($ogameserver == 'ogame.com.cn'){
			$galastring = str_replace("联盟 ","Alliance ",$galastring); // Leerzeichen ist wichtig !!!
			$galastring = str_replace("排名 ","Rank ",$galastring);
			$galastring = str_replace("玩家 ","Player ",$galastring);
			$galastring = str_replace("星球 ","Planet ",$galastring);
			$galastring = str_replace("内容","Properties",$galastring); //property of moon
			$galastring = str_replace("资源:","Resources:",$galastring); //Deb
			$galastring = str_replace("28 天没动静	I","days inactive I",$galastring);
			$galastring = str_replace("28 天没动静 I","days inactive I",$galastring);
		} else if($ogameserver == 'ogame.tw') {
			$galastring = str_replace("聯盟 ","Alliance ",$galastring); // Leerzeichen ist wichtig !!!
			$galastring = str_replace("排名 ","Rank ",$galastring);
			$galastring = str_replace("玩家 ","Player ",$galastring);
			$galastring = str_replace("星球 ","Planet ",$galastring);
			$galastring = str_replace("內容","Properties",$galastring); //property of moon
			$galastring = str_replace("資源:","Resources:",$galastring); //Deb
			$galastring = str_replace("28 天沒動靜	I","days inactive I",$galastring);
			$galastring = str_replace("28 天沒動靜 I","days inactive I",$galastring);
		}
		
		$galastring = str_replace("\r","",$galastring); // Windows Linebreaks zu Linux Linebreaks konvertieren
		$galastring = trim(substr($galastring,strpos($galastring,"days inactive I")+strlen("days inactive I")));

		$temp = array();
		$line = explode("\n",$galastring);

		$j = 0;

		foreach ($line as $var) {
			$needreset = false;
			// Allyrank
			$var = trim($var);
			if (substr($var,0,8) == "Alliance") {
				$pos = strpos($var,"Rank");
				$allyname = trim(substr($var, strlen("Alliance")+1, $pos-1-strlen("Alliance")-1));
				$var = trim(substr($var,$pos+strlen("Rank")+1));
				$tmp = explode(" ",$var);
				$tmpc = count($tmp);
				if(!empty($allyname) && $tmpc >=4 && !empty($tmp[1])) {
					$allymember = str_replace("#","",$tmp[$tmpc-2]);
					$allyrank = str_replace("#","",$tmp[0]);
					if(!isset($allystats[$allyname]) && is_numeric($allyrank) && is_numeric($allymember))
						$allystats[$allyname] = array($allyrank,$allymember);
				}
			}
			//  Player MACHINE on rank 73 || MACHINE ranked 73 (new version)
			if ((substr($var,0,6) == "Player") || ($ogameserver == "ogame.org" && !empty($var) && preg_match("/^.+\sRank\s\d+$/",$var) == 1)) { // for new english version which has not always Player ... at first!
				// Spielerplatzierung ermitteln
				$pn = "";
				if(preg_match('/^(Player\s)?(.+)\sRank\s(\d+)$/', $var, $matches) == 1) {
					$pn = trim($matches[2]);
					$ps = trim($matches[3]);
				} else if(preg_match('/^Player\s(.+)$/', $var, $matches) == 1) {
					$pn = trim($matches[1]);
					$ps = -1;
				}
				if(!empty($pn) && !isset($playerstats[$pn]))
					$playerstats[$pn] = array('status'=>'', 'ally'=>'', 'rank'=>-1);
				if(!empty($pn)) $playerstats[$pn]['rank'] = $ps;
			}

			if (substr($var,0,10) == "Properties") {
				// Mondgr?ermitteln
				// Pr?b IE (keine \t sondern nur Leerzeichen)
				if (strpos($line[$j+1],"\t") === false) {
					// IE Handling
					$tmp = explode(" ",$line[$j+1]);
					$temp['moonsize'] = str_replace(".", "", $tmp[1]);
					$temp['moon'] = 1;
				} else {
					// Mozilla und co.
					$tmp = explode("\t",$line[$j+1]);
					$temp['moonsize'] = str_replace(".", "", $tmp[1]);
				}
			}
			
			if (substr($var,0,10) == "Resources:") {
				// Tr?eld ermitteln
				// Pr?b IE (keine \t sondern nur Leerzeichen)
				if (strpos($line[$j+1],"\t") === false) {
					// IE Handling
					$tmp = explode(" ",$line[$j+1]);
					$temp['metal'] = str_replace(".","",$tmp[1]);
					$tmp = explode(" ",$line[$j+2]);
					$temp['crystal'] = str_replace(".","",$tmp[1]);
				} else {
					// Mozilla und co.
					$tmp = explode("\t",$line[$j+1]);
					$temp['metal'] = str_replace(".","",$tmp[1]);
					$tmp = explode("\t",$line[$j+2]);
					$temp['crystal'] = str_replace(".","",$tmp[1]);
				}
			}

			// Planet Schweiz [1:1:12]
			if (substr($var,0,6) == "Planet") {
				// Position ermitteln
				$tmp = explode(" ",$var);
				$temp['position'] = trim($tmp[count($tmp)-1]);
				if (isset($temp['moon'])) $infoarray[$temp['position']]['moon'] = $temp['moon']; // IE !!!
				if (isset($temp['moonsize'])) $infoarray[$temp['position']]['moonsize'] = $temp['moonsize'];
				if (isset($temp['metal'])) $infoarray[$temp['position']]['metal'] = $temp['metal'];
				if (isset($temp['crystal'])) $infoarray[$temp['position']]['crystal'] = $temp['crystal'];
				//each section always begans with 'Player' and ends with 'Planet' or 'Alliance'.
				//each section must has 'Planet' graph
				//unset old $temp, begin a new one				
				unset($temp);
				$temp = array();				
			}			

			$j++;			
		}

	
		// DB Verbindung erstellen
		mysql_connect($this->dbhost, $this->dbusername, $this->dbpassword) or die(PARSER_ERROR3);
		mysql_select_db($this->dbname) or die(PARSER_ERROR2);

		if (count($infoarray) > 1)
		foreach ($infoarray as $data) {
			if ($data['galaxie'] > 0 && $data['galaxie'] < 51 && $data['system'] > 0 && $data['system'] < 500 && $data['planetnummer'] > 0 && $data['planetnummer'] < 16) {
				$query = "select notices, reports from $this->tablename where userid=$userid and galaxie=".$data['galaxie']." and system=".$data['system']." and planet=".$data['planetnummer'];
				$res = mysql_query($query);
				if (!$res) {
					$this->error = $query." ".mysql_error();
					return false;
				}
				$notices = 'false';
				$reports = 'false';
				if($line = mysql_fetch_assoc($res)){
					$notices = $line['notices'];
					$reports = $line['reports'];
				}
				$query = "REPLACE INTO $this->tablename "."SET userid=$userid, galaxie=".$data['galaxie'].", system=".$data['system'].", planet=".$data['planetnummer'] .
				", coordinates='". $data['galaxie'].":".$data['system'].":".$data['planetnummer']. "' ".
				", mond='".$data['moon']."', " . "ally='".$data['ally']."',planetname='".$data['planetname']."',spielername='".$data['playername']."', ".
				"zeit='".time()."', ";
				if (isset($data['moonsize'])) $query .= "mondgr='".$data['moonsize']."', ";
				if (isset($data['metal'])) $query .= "metall='".$data['metal']."', ";
				if (isset($data['crystal'])) $query .= "kristall='".$data['crystal']."', ";
				$query .= "notices='$notices', reports='$reports'";
				
				if (!$return) {
					mysql_query($query) or die(mysql_error());
				} else {
					$returnarray = array_push($query);
				}
			}
		}
		//ally stats
		foreach ($allystats as $allyname => $data) {
			$query = "INSERT IGNORE INTO $this->astatsname (userid, allyname) values($userid, '" . mysql_real_escape_string($allyname) ."')";
			if(!$return) {
				mysql_query($query) or die(mysql_error());
			} else {
				$returnarray = array_push($query);
			}
			$query = "UPDATE $this->astatsname set rank=". $data[0] . ", members=". $data[1] .", last_update='". date("Y-m-d H:i:s") ."'" .
				 " WHERE userid=$userid and allyname='" . mysql_real_escape_string($allyname) ."'";
			if(!$return) {
				mysql_query($query) or die(mysql_error());
			} else {
				$returnarray = array_push($query);
			}			
		}
		//player stats
		foreach ($playerstats as $playername => $playerarray) {
			$query = "INSERT IGNORE INTO $this->pstatsname (userid, playername) values($userid, '" . mysql_real_escape_string($playername) . "')";
			if(!$return) {
				mysql_query($query) or die(mysql_error());
			} else {
				$returnarray = array_push($query);
			}
			
			$query = "UPDATE $this->pstatsname set status='" . $playerarray['status'] . "', ally='" . $playerarray['ally'] . "', rank=" . $playerarray['rank'] .", last_update='". date("Y-m-d H:i:s") ."' WHERE userid=$userid and playername='" . mysql_real_escape_string($playername) ."'";
			if(!$return) {
				mysql_query($query) or die(mysql_error());
			} else {
				$returnarray = array_push($query);
			}			
		}
		
		echo "<a href=\"view.php?gala=$galaxie&system=$system\">" . "$galaxie:$system" . "</a> " .PARSER_INFO1. "<br>";

		if ($return) return $returnarray;
		else return true;
	}


	/**
	* @return boolean
	* @param String $tablename Name der Tabelle mit den Downloads
	* @desc Setzt den Tabellennamen f? Datenbankverbindung
    */
	function _set_tablename($tablename) {
		if (!empty($tablename)) {
			$this->tablename = $tablename;
			return true;
		} else {
			$this->error = "Der Tabellenname ist leer!";
			return false;
		}
	}


	/**
	* @return boolean
	* @param String $dbusername Datenbanknutzername
	* @desc Setzt den Username f? Datenbankverbindung
    */
	function _set_dbusername($dbusername) {
		if (!empty($dbusername)) {
			$this->dbusername = $dbusername;
			return true;
		} else {
			$this->error = "Der Username ist leer!";
			return false;
		}
	}

	/**
	* @return boolean
	* @param String $dbpassword Datenbankpasswort
	* @desc Setzt das Passwort f? Datenbankverbindungen
 	*/
	function _set_dbpassword($dbpassword) {
			$this->dbpassword = $dbpassword;
			return true;
	}

	/**
	* @return boolean
	* @param String $dbname Datenbankname
	* @desc Setzt den Namen der zu verwendenden Datenbank
 	*/
	function _set_dbname($dbname) {
		if (!empty($dbname)) {
			$this->dbname = $dbname;
			return true;
		} else {
			$this->error = "Der Datenbankname ist leer!";
			return false;
		}
	}

	/**
	* @return boolean
	* @param String $dbhost Datenbankadresse
	* @desc Setzt die Host-Adresse f? Datenbank
 	*/
	function _set_dbhost($dbhost) {
		$this->dbhost = $dbhost;
		return true;
	}

	/**
	* @return boolean
	* @desc Testet ob die Verbindung zur Datenbank funktioniert
 	*/
	function _db_connection_works() {
		mysql_connect($this->dbhost, $this->dbusername, $this->dbpassword) or die(PARSER_ERROR3);
		mysql_select_db($this->dbname) or die(PARSER_ERROR2);
		mysql_close();
		return true;
	}

}




?>